#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include <string.h>

int sub1(lua_State* L)
{  
    int a = lua_tonumber(L, 2);
    int b = lua_tonumber(L, 1);
    lua_pop(L, 2);
    int r = a - b;
    lua_pushnumber(L, r);
    return 1;
}
    

int main()
{
    //创建新的lua state
    lua_State *L = luaL_newstate();
    //加载所有标准库
    luaL_openlibs(L);

    /*1.从lua文件中加载全局变量*/
    //加载person.lua文件
    int r = luaL_loadfile(L, "person.lua");
    //执行加载的lua块
    r = lua_pcall(L, 0, 0, 0);
    //获取lua栈顶元素的索引，用偏移指向栈中元素
    int stack_base = lua_gettop(L);
    //把全局变量的值留在栈中
    lua_getglobal(L, "name");
    lua_getglobal(L, "age");
    lua_getglobal(L, "sex");
    //从栈中取值
    const char* name_p = lua_tostring(L, stack_base + 1);
    char name[32], sex[32];
    int age = lua_tointeger(L, stack_base + 2);
    const char* sex_p = lua_tostring(L, stack_base + 3);
    strcpy(name, name_p);
    strcpy(sex, sex_p);
    //清理栈
    lua_pop(L, 3);
    printf("name = %s, age = %d, sex = %s\n", name, age,sex);


    /*2.把变量传递给lua文件，并打印*/
    //栈中压入值
    lua_pushstring(L, "www");
    lua_pushstring(L, sex);
    lua_pushinteger(L, 20);
    //从栈顶分配元素
    lua_setglobal(L, "age1");
    lua_setglobal(L, "sex1");
    lua_setglobal(L, "name1");
    //加载文件person.lua
    r = luaL_loadfile(L, "person.lua");
    //执行加载的lua块
    r = lua_pcall(L, 0, 0, 0);


    /*3.调用lua函数求和*/
    int num1 = 1, num2 = 2;
    //将add函数压入栈中
    lua_getglobal(L, "add");
    //压入两个参数
    lua_pushnumber(L, num1);
    lua_pushnumber(L, num2);
    //执行加载的lua块
    lua_pcall(L, 2, 1, 0);
    //从栈顶获取返回值
    r = lua_tointeger(L, -1);
    printf("the add is %d\n", r);
    //关闭lua，并清理


    /*4.写一个函数，在lua中可调用*/

    lua_register(L, "sub1", sub1);
    r = luaL_dofile(L, "call.lua");

    lua_close(L);
    return 0;
}